package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.AuthConstant;
import com.powernode.domain.SysLoginUser;
import com.powernode.mapper.SysLoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;



    /**
     * 先判断前台会员还是后台管理员
     * 和前端约定好 在授权的请求头里面放一个标识
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String loginType = requestAttributes.getRequest().getHeader(AuthConstant.LOGIN_TYPE);
        if (!StringUtils.hasText(loginType)) {
            return null;
        }
        switch (loginType) {
            case AuthConstant.SYS_USER:
                // 后台管理员
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username)
                );
                if (!ObjectUtils.isEmpty(sysLoginUser)){
                    //处理权限
                    List<String> auths = sysLoginUserMapper.selectAuthsBySysUserId(sysLoginUser.getUserId());
                    if (!CollectionUtils.isEmpty(auths)){
                        sysLoginUser.setAuths(auths);
                    }
                }
                return sysLoginUser;
            case AuthConstant.MEMBER:
                // 前台会员
            default:
                return null;
        }
    }
}
